package com.pijunn.profile

import org.codehaus.groovy.grails.web.mapping.LinkGenerator;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;

import com.pijunn.common.template.TemplateHolder;
import com.pijunn.security.SecRole;
import com.pijunn.security.SecUserSecRole;
import com.pijunn.users.AppUser

class ProfileService {
	
	static transactional = true
	
	def emailerService
	def grailsLinkGenerator
	def userRole = SecRole.findByAuthority('ROLE_USER')

    def createUser(AppUser user, tempPassword = null) {
		try {
			if (!user.save(flush: true)) 
				throw new IllegalStateException("User has errors")
			def userRole = SecUserSecRole.create(user, userRole, true)
// Why does this evaluate to true when creation succeeded?
//			if (!userRole)
//				throw new IllegalStateException("Role creation failed")
		}
		catch(DataIntegrityViolationException e) {
			throw new IllegalStateException(e)
		}
		
		def bindingName = "registration"
		def link = grailsLinkGenerator.link([controller: 'profile', action: 'confirm', id: user.createTime.getTime(), absolute: true])
		def registration = [link: link, user: user, tempPassword: tempPassword]
		def h = new TemplateHolder([bindingName: bindingName, to: [user.contactEMail], subject: "Welcome to Pijunn!", binding: registration]);

		if (user.passwordExpired) {
			h.bindingName = "adminCreation"
			h.binding.link = grailsLinkGenerator.link([controller: 'labeledItem', action: 'create', absolute: true])
		}
		emailerService.sendNotificationEmail(h)
		
		true
    }
	
	@Transactional(readOnly = true)
	def getCountsForProperty(def property) {
		return AppUser.withCriteria {
			projections {
				groupProperty property
				rowCount()
			}
		}
	}
	
	@Transactional(readOnly = true)
	def getIncompletePhoneContactCounts() {
		return AppUser.withCriteria {
			eq('contactCellPhone', '')
			eq('contactOtherPhone', '')
			eq('contactSkypeId', '')
			projections {
				rowCount()
			}
		}
	}
}
